/**
 * Reads the related file plan fragment (defined with scope argument) from
 * server and puts it into model.
 * <p>
 * Called as : alfresco/service/util/fileplan-fragment?scope=640-659
 */
function main() {
	// get root folder
	var rootFolder = companyhome.childByNamePath("Sites").childByNamePath("rm")
			.childByNamePath("documentLibrary");

	var scopeinterval = args.scope.split("-");
	var startindex = scopeinterval[0];
	var endindex = scopeinterval[1];

	// get summary object
	var rootObj = getFragment(rootFolder, startindex, endindex);

	// stringify root folder
	var jsonString = jsonUtils.toJSONString(rootObj);
	model.jsonString = jsonString;
}

/**
 * Retrieves the necessary properties of the alfresco node and creates a new
 * summary object that is suitable to stringify.
 * 
 * @param alfNode
 *            alfresco node.
 * @return summary object that is suitable to stringify.
 */
function summarizeObject(alfNode) {
	// object to stringify
	var rootObj = {};

//	var nodeRefCode = alfNode.properties["{http://www.alfresco.org/model/recordsmanagement/1.0}ts13298RefCodePart"];
//	if (nodeRefCode != "" && nodeRefCode != null && nodeRefCode != undefined) {
	// use just folders
	if(alfNode.isContainer){
		// get necessary properties
		rootObj.name = alfNode.properties.name;
		rootObj.nodeRef = alfNode.nodeRef;
		rootObj.type = alfNode.type;
		var nodeRefCode = alfNode.properties["{http://www.alfresco.org/model/recordsmanagement/1.0}ts13298RefCodePart"];
		if (nodeRefCode != "" && nodeRefCode != null && nodeRefCode != undefined) {
			rootObj.refcodepart = nodeRefCode;
		}
		// recursively get children objects
		var children = new Array();
		if (alfNode.children.length > 0) {
			var temp = 0;
			for ( var child in alfNode.children) {
				children[temp] = summarizeObject(alfNode.children[temp]);
				temp = temp + 1;
			}
		}
		rootObj.children = children;
	}
//	}

	// return summary
	return rootObj;
}

/**
 * Retrieves the fileplan fragment whose refCode is between startindex and
 * endindex.
 * 
 * @param rootnode
 *            Fileplan root directory.
 * @param startindex
 *            start index
 * @param endindex
 *            end index
 * @return file plan fragment
 */
function getFragment(rootNode, startindex, endindex) {
	var rootObj = {};
	var temp = 0;
	var children = new Array();
	for ( var i = 0; i < rootNode.children.length; i++) {
		var nodeRefCode = rootNode.children[i].properties["{http://www.alfresco.org/model/recordsmanagement/1.0}ts13298RefCodePart"];
		if (nodeRefCode != "" && nodeRefCode != null
				&& nodeRefCode != undefined && nodeRefCode >= startindex
				&& nodeRefCode <= endindex) {
			children[temp] = summarizeObject(rootNode.children[i]);
			temp = temp + 1;
		}
	}
	// object to stringify
	rootObj.children = children;

	// return summary
	return rootObj;
}

main();